<?php

namespace App\Http\Controllers\Api;

use App\Models\Role;
use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class RoleController extends BaseController
{
    /**
     * 获取角色列表
     */
    public function index(Request $request)
    {
        try {
            $query = Role::query();

            // 搜索
            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('code', 'like', "%{$search}%");
                });
            }

            // 状态筛选
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            // 分页
            $perPage = $request->get('per_page', 15);
            $roles = $query->paginate($perPage);

            return $this->paginate($roles, '获取角色列表成功');
        } catch (\Exception $e) {
            return $this->error('获取角色列表失败：' . $e->getMessage());
        }
    }

    /**
     * 创建角色
     */
    public function store(Request $request)
    {
        try {
            $data = $this->validateRequest($request, [
                'name' => 'required|string|max:100|unique:roles',
                'code' => 'required|string|max:50|unique:roles',
                'description' => 'nullable|string|max:500',
                'status' => 'required|in:active,inactive',
            ]);

            $role = Role::create($data);

            // 记录操作日志
            $this->logOperation('create', 'role', [
                'role_id' => $role->id,
                'role_name' => $role->name
            ]);

            return $this->success($role, '创建角色成功', 201);
        } catch (\Exception $e) {
            return $this->error('创建角色失败：' . $e->getMessage());
        }
    }

    /**
     * 获取角色详情
     */
    public function show(Role $role)
    {
        try {
            $role->load(['users' => function ($query) {
                $query->select('id', 'username', 'phone');
            }]);

            return $this->success($role, '获取角色详情成功');
        } catch (\Exception $e) {
            return $this->error('获取角色详情失败：' . $e->getMessage());
        }
    }

    /**
     * 更新角色
     */
    public function update(Request $request, Role $role)
    {
        try {
            $data = $this->validateRequest($request, [
                'name' => ['required', 'string', 'max:100', Rule::unique('roles')->ignore($role->id)],
                'code' => ['required', 'string', 'max:50', Rule::unique('roles')->ignore($role->id)],
                'description' => 'nullable|string|max:500',
                'status' => 'required|in:active,inactive',
            ]);

            $role->update($data);

            // 记录操作日志
            $this->logOperation('update', 'role', [
                'role_id' => $role->id,
                'changes' => $data
            ]);

            return $this->success($role, '更新角色成功');
        } catch (\Exception $e) {
            return $this->error('更新角色失败：' . $e->getMessage());
        }
    }

    /**
     * 删除角色
     */
    public function destroy(Role $role)
    {
        try {
            // 检查是否有用户使用此角色
            if ($role->users()->count() > 0) {
                return $this->error('该角色正在被用户使用，无法删除');
            }

            $role->delete();

            // 记录操作日志
            $this->logOperation('delete', 'role', [
                'role_id' => $role->id,
                'role_name' => $role->name
            ]);

            return $this->success(null, '删除角色成功');
        } catch (\Exception $e) {
            return $this->error('删除角色失败：' . $e->getMessage());
        }
    }

    /**
     * 为角色分配权限
     */
    public function assignPermissions(Request $request, Role $role)
    {
        try {
            $data = $this->validateRequest($request, [
                'permissions' => 'required|array',
                'permissions.*' => 'string',
            ]);

            $role->setPermissions($data['permissions']);
            $role->save();

            // 记录操作日志
            $this->logOperation('assign_permissions', 'role', [
                'role_id' => $role->id,
                'permissions' => $data['permissions']
            ]);

            return $this->success($role, '权限分配成功');
        } catch (\Exception $e) {
            return $this->error('权限分配失败：' . $e->getMessage());
        }
    }

    /**
     * 移除角色的权限
     */
    public function removePermissions(Request $request, Role $role)
    {
        try {
            $data = $this->validateRequest($request, [
                'permissions' => 'required|array',
                'permissions.*' => 'string',
            ]);

            foreach ($data['permissions'] as $permission) {
                $role->removePermission($permission);
            }
            $role->save();

            // 记录操作日志
            $this->logOperation('remove_permissions', 'role', [
                'role_id' => $role->id,
                'permissions' => $data['permissions']
            ]);

            return $this->success($role, '权限移除成功');
        } catch (\Exception $e) {
            return $this->error('权限移除失败：' . $e->getMessage());
        }
    }
}
